package com.davy.gridpoint.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.GnssStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.widget.AppCompatButton;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.davy.gridpoint.BaseActivity;
import com.davy.gridpoint.DavyApp;
import com.davy.gridpoint.R;
import com.davy.gridpoint.ScreenManager;
import com.davy.gridpoint.adapter.SourceAdapter;
import com.davy.gridpoint.bean.ChooseBean;
import com.davy.gridpoint.http.CommonHttpConsts;
import com.davy.gridpoint.http.HttpCallbackData;
import com.davy.gridpoint.http.HttpClient;
import com.davy.gridpoint.http.JsonBeanData;
import com.davy.gridpoint.qlxj.TakeActivity;
import com.davy.gridpoint.qlxj.adapter.ImgAdapter;
import com.davy.gridpoint.utils.DeviceIdHelper;
import com.davy.gridpoint.utils.DialogUitl;
import com.davy.gridpoint.utils.GPSToGCJ;
import com.davy.gridpoint.utils.LogUtils;
import com.davy.gridpoint.utils.SPUtils;
import com.davy.gridpoint.utils.StringUtils;
import com.davy.gridpoint.utils.ToastUtil;
import com.davy.gridpoint.view.CustomImageView;
import com.davy.gridpoint.view.IndicatorProgressBar;
import com.davy.gridpoint.view.MyRecyclerView;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;

import java.io.File;
import java.io.IOException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

public class GridMainActivity extends BaseActivity {
    private long mExitTime = 0;//退出程序
    private static final int REQUEST_LOCATION_PERMISSION_CODE = 1;
    private final int REQUEST_IMG = 1001;
    private TextView tvSelect, tvLine;
    private EditText etMileage1;
    private RadioGroup groupXb;
    private AppCompatButton btnConfirm;
    private boolean isLocation = true;
    protected LocationManager locationManager;
    private String mLongitude, mLatitude, mAltitude;
    protected DecimalFormat decimalFormat;
    protected DecimalFormat decimalFormat2;
    private ArrayList<ChooseBean> stationList;
    private ArrayList<ChooseBean> lineList;
    private MyRecyclerView recyclerImg;
    private ImgAdapter imgAdapter;
    private ArrayList<Map> imgList;
    private Activity mActivity;
    private String inXb = "";
    private String strSelect = "";
    private String pwsSelect = "";
    private String lineId = "";
    private String lineName = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_main);
        mActivity = this;
        statusbar4();
        initView();
        String insertTime = SPUtils.get(mContext, "benS", "") + "";
        if (!StringUtils.isEmpty(insertTime)) {
            upLogInfo(insertTime);
        }

        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
        } else {
            LogUtils.e("TAG", "权限已经授予");
            // 权限已经授予，可以进行位置相关的操作
            initLocation();
        }

        initData();
        initClick();
    }

    private void initData() {
        ChooseBean chooseBean2 = new ChooseBean();
        chooseBean2.setName("西安工务段");
        chooseBean2.setPid("pws001");
        ChooseBean chooseBean3 = new ChooseBean();
        chooseBean3.setName("宝鸡工务段");
        chooseBean3.setPid("pws002");
        ChooseBean chooseBean4 = new ChooseBean();
        chooseBean4.setName("安康工务段");
        chooseBean4.setPid("pws003");
        ChooseBean chooseBean5 = new ChooseBean();
        chooseBean5.setName("汉中工务段");
        chooseBean5.setPid("pws004");
        ChooseBean chooseBean6 = new ChooseBean();
        chooseBean6.setName("阎良工务段");
        chooseBean6.setPid("pws005");
        ChooseBean chooseBean7 = new ChooseBean();
        chooseBean7.setName("延安工务段");
        chooseBean7.setPid("pws006");
        ChooseBean chooseBean8 = new ChooseBean();
        chooseBean8.setName("绥德工电段");
        chooseBean8.setPid("pws008");
        ChooseBean chooseBean9 = new ChooseBean();
        chooseBean9.setName("西安高铁基础设施段");
        chooseBean9.setPid("pws009");
        ChooseBean chooseBean10 = new ChooseBean();
        chooseBean10.setName("延安运营维修段");
        chooseBean10.setPid("pws010");

        stationList.add(chooseBean2);
        stationList.add(chooseBean3);
        stationList.add(chooseBean4);
        stationList.add(chooseBean5);
        stationList.add(chooseBean6);
        stationList.add(chooseBean7);
        stationList.add(chooseBean8);
        stationList.add(chooseBean9);
        stationList.add(chooseBean10);

    }

    private void initView() {
        stationList = new ArrayList<>();
        imgList = new ArrayList<>();
        lineList = new ArrayList<>();
        decimalFormat = new DecimalFormat("#.00000000");
        decimalFormat2 = new DecimalFormat("#.00");
        strSelect = SPUtils.get(mContext, "strSelect", "") + "";
        pwsSelect = SPUtils.get(mContext, "pwsSelect", "") + "";
        LogUtils.e("TAG", "pwsSelect" + pwsSelect);

        tvSelect = findViewById(R.id.tvSelect);
        tvLine = findViewById(R.id.tvLine);
        groupXb = findViewById(R.id.groupXb);
        recyclerImg = findViewById(R.id.recyclerImg);
        btnConfirm = findViewById(R.id.btnConfirm);
        etMileage1 = findViewById(R.id.etMileage1);
        if (StringUtils.isEmpty(strSelect)) {
            tvSelect.setText("请选择工务段");
            tvSelect.setTextColor(mContext.getResources().getColor(R.color.orange_salmon));
        } else {
            tvSelect.setText(strSelect);
            tvSelect.setTextColor(mContext.getResources().getColor(R.color.tv333));
            GetPwsLine();
        }

        destfiledir = Environment.getExternalStorageDirectory().getPath();
        LogUtils.e("tag", "destfiledir:" + destfiledir);
        mProgress = findViewById(R.id.update_progress);
        rl_softu = findViewById(R.id.rl_softu);
        lyDialog = findViewById(R.id.lyDialog);
        tvContext = findViewById(R.id.tvContext);
        tvDialogCancel = findViewById(R.id.tvDialogCancel);
        tvDialogConfirm = findViewById(R.id.tvDialogConfirm);
        rl_softu.setVisibility(View.GONE);
        rl_softu.setOnClickListener(v -> {
        });
        lyDialog.setOnClickListener(v -> {
        });

        tvDialogCancel.setOnClickListener(v -> lyDialog.setVisibility(View.GONE));
        tvDialogConfirm.setOnClickListener(v -> {
            lyDialog.setVisibility(View.GONE);
            rl_softu.setVisibility(View.VISIBLE);
            downloadNewFile();
        });

        upVersions();
    }

    private void initClick() {
        tvSelect.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) return;

            dismiss();
            if (stationList.size() == 0) {
                ToastUtil.show("没有工务段数据");
                return;
            }
            initPopupWindow(tvSelect, stationList, 1);
        });

        tvLine.setOnClickListener(v -> {
            if (StringUtils.isFastClick()) return;

            dismiss();
            if (lineList.size() == 0) {
                ToastUtil.show("没有线路数据");
                return;
            }
            initPopupWindow(tvLine, lineList, 2);
        });

        groupXb.setOnCheckedChangeListener((group, checkedId) -> {
            switch (checkedId) {
                case R.id.radioXb1:
                    inXb = "上行";
                    break;
                case R.id.radioXb2:
                    inXb = "下行";
                    break;
                case R.id.radioXb3:
                    inXb = "单线";
                    break;
                case R.id.radioXb4:
                    inXb = "双线";
                    break;
            }
        });

        recyclerImg.setLayoutManager(new GridLayoutManager(mContext, 3, RecyclerView.VERTICAL, false));
        imgAdapter = new ImgAdapter(mContext, imgList);
        recyclerImg.setAdapter(imgAdapter);
        imgAdapter.setItemClickListener(new ImgAdapter.ItemClickListener() {
            @Override
            public void addClick(int position) {
                if (StringUtils.isFastClick()) {
                    return;
                }

                Intent intent = new Intent(mContext, TakeActivity.class);
                startActivityForResult(intent, REQUEST_IMG);
            }

            @Override
            public void delClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }
                imgList.remove(position);
                imgAdapter.setData(imgList);
            }

            @Override
            public void getClick(int position, Map mList) {
                if (StringUtils.isFastClick()) {
                    return;
                }

                int type = Double.valueOf(StringUtils.isEmpty(mList.get("type") + "") ? "0" : mList.get("type") + "").intValue();
                if (type == 1 || type == 2) {
                    String img = mList.get("img") + "";
                    Double isBt = 1.0; //1：保存 2：提交
                    if (mList.containsKey("isBt")) {
                        isBt = Double.valueOf(mList.get("isBt") + "");
                    }

                    if (isBt.intValue() == 2) {
                        if (!img.startsWith("http")) {
                            img = HttpClient.imgUrl + img.replace("/storage/emulated/0/Davy/", "");
                        }
                    }

                    imgDialog(img);
                }
            }
        });

        btnConfirm.setOnClickListener(v -> {
            if (StringUtils.isEmpty(pwsSelect)) {
                ToastUtil.show("请选择工务段！");
                return;
            }
            if (StringUtils.isEmpty(lineName)) {
                ToastUtil.show("请选择线路！");
                return;
            }
            if (StringUtils.isEmpty(inXb)) {
                ToastUtil.show("请选择行别！");
                return;
            }
            String mileage1 = etMileage1.getText().toString().trim();
            if (StringUtils.isEmpty(mileage1)) {
                ToastUtil.show("请输入里程信息");
                return;
            }

            if (imgList.isEmpty()) {
                ToastUtil.show("请添加图片！");
                return;
            }
            if (StringUtils.isFastClick()) {
                return;
            }
            List<String> fileName = new ArrayList<>();
            List<File> files = new ArrayList<>();
            int i = 0;
            while (imgList.size() > i) {
                File file = new File(imgList.get(i).get("img").toString().trim());
                if (file.isFile()) {
                    files.add(file);
                    fileName.add(file.getName());
                }
                i++;
            }

            Map<String, Object> gridMap = new HashMap<>();
            gridMap.put("pws_id", pwsSelect);
            gridMap.put("pws_name", strSelect);
            gridMap.put("line_id", lineId);
            gridMap.put("line_name", lineName);
            gridMap.put("imei", DeviceIdHelper.getDeviceId(mContext));
            gridMap.put("geo_end_milege", "");
            gridMap.put("geo_start_milege", mileage1);
            gridMap.put("xb", inXb);
            gridMap.put("type", "");
            gridMap.put("longitude", mLongitude);
            gridMap.put("latitude", mLatitude);
            gridMap.put("altitude", mAltitude);
            //gridMap.put("img_path", fileName);

            FreedomPoint(gridMap, fileName, files);
        });
    }

    private void FreedomPoint(Map gridMap, List<String> fileName, List<File> files) {
        String json = new Gson().toJson(gridMap);
        LogUtils.e("TAG", "json:" + json);
        LogUtils.e("TAG", "fileName:" + fileName.toString());

        HttpClient.getInstance().postData(CommonHttpConsts.FreedomPoint, "FreedomPoint")
                .params("json", json)
                .addUrlParams("file_name", fileName)
                .addFileParams("file", files)
                .execute(new HttpCallbackData() {

                    @Override
                    public void onSuccess(int code, String msg, String info) {
                        LogUtils.e("TAG", "info:" + info);
                        ToastUtil.showNew(mContext, msg);
                        if (code == 200) {
                            imgList.clear();
                            etMileage1.setText("");
                            imgList = new ArrayList<>();
                            imgAdapter.setData(imgList);
                        }
                    }

                    @Override
                    public void onError() {
                        super.onError();
                        ToastUtil.showNew(mContext, StringUtils.error_context);
                    }

                    @Override
                    public boolean showLoadingDialog() {
                        return true;
                    }

                    @Override
                    public Dialog createLoadingDialog() {
                        return DialogUitl.loginAuthDialog(mContext);
                    }
                });
    }

    private void upLogInfo(String insertTime) {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("time", insertTime);
        jsonObject.put("imei", DeviceIdHelper.getDeviceId(mContext));
        jsonObject.put("loginfo", SPUtils.get(mContext, "benE", ""));
        jsonObject.put("versions", StringUtils.getVerName(mContext));
        jsonObject.put("uname", SPUtils.get(mContext, "userPhone", ""));

        LogUtils.e("TAG", "jsonObject--->" + jsonObject.toString());

        HttpClient.getInstance().post(HttpClient.httpUrl + CommonHttpConsts.upLogInfo, "upLogInfo").upJson(jsonObject.toString()).execute(new HttpCallbackData() {

            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 200) {
                    SPUtils.put(mContext, "benE", "");
                    SPUtils.put(mContext, "benS", "");
                }
            }
        });
    }

    //系统升级
    private IndicatorProgressBar mProgress;
    private RelativeLayout rl_softu;
    private LinearLayout lyDialog;
    private TextView tvContext;
    private String destfiledir;
    private String downloadurl;
    private String app_name = "";
    private TextView tvDialogCancel, tvDialogConfirm;
    private int isforcedupdate = 0;

    private void upVersions() {
        HttpClient.getInstance().getData(CommonHttpConsts.upVersion, "upVersion").params("version", StringUtils.getVerName(mContext)).params("railway", "wangge").execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);
                if (code == 200 && !StringUtils.isEmpty(info)) {
                    String string = StringUtils.decompressForGzip(info);
                    Map dataMap = JSON.parseObject(string, Map.class);
                    if (dataMap.size() > 0) {
                        downloadurl = dataMap.get("url") + "";
                        app_name = dataMap.get("name") + "";
                        tvContext.setText(dataMap.get("content") + "");
                        String isfo = dataMap.get("force") + "";
                        if (!StringUtils.isEmpty(isfo)) {
                            isforcedupdate = Integer.valueOf(isfo);
                        }
                        lyDialog.setVisibility(View.VISIBLE);
                        if (isforcedupdate == 1) {
                            tvDialogCancel.setVisibility(View.GONE);
                        } else {
                            tvDialogCancel.setVisibility(View.VISIBLE);
                        }
                    }
                } else {
//                            ToastUtil.show(msg);
                }
            }

            @Override
            public void onError(Response<JsonBeanData> response) {
                super.onError(response);
                ToastUtil.show(StringUtils.error_context);
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }
        });
    }

    private void downloadNewFile() {
        OkGo.<File>get(downloadurl).tag(mContext).execute(new FileCallback(destfiledir, app_name) {
            @Override
            public void onSuccess(Response<File> response) {
                String s = destfiledir + "/" + app_name;
                rl_softu.setVisibility(View.GONE);
                installApk(s);
            }


            @Override
            public void downloadProgress(Progress progress) {
                super.downloadProgress(progress);
                LogUtils.e("TAG", "下载进度：" + (int) (progress.fraction * 100));
                mProgress.setProgress((int) (progress.fraction * 100));
            }

            @Override
            public void onError(Response<File> response) {
                super.onError(response);
                runOnUiThread(() -> {
                    rl_softu.setVisibility(View.GONE);
                    ToastUtil.show("网络中断，请稍后再试！");
                });
            }
        });
    }

    /**
     * 安装apk
     */
    public void installApk(String apkPath) {
        if (TextUtils.isEmpty(apkPath)) {
            ToastUtil.show("更新失败！未找到安装包");
            return;
        }

        LogUtils.e("TAG", "开始执行安装: " + apkPath);
        File apkFile = new File(apkPath);
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            LogUtils.e("TAG", "版本大于 N ，开始使用 fileProvider 进行安装");
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(mContext, "com.davy.gridpoint.fileprovider", apkFile);
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        } else {
            LogUtils.e("TAG", "正常进行安装");
            intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive");
            mContext.startActivity(intent);
        }
    }

    private PopupWindow popupWindow;

    private void initPopupWindow(View data, ArrayList<ChooseBean> popList, int ds) {
        View view = View.inflate(mContext, R.layout.layout_popup_view, null);
        RecyclerView recyclerPop = view.findViewById(R.id.recyclerPop);
        recyclerPop.setLayoutManager(new LinearLayoutManager(mContext));
        SourceAdapter sourceAdapter = new SourceAdapter(mContext, popList);
        recyclerPop.setAdapter(sourceAdapter);
        popupWindow = new PopupWindow(view, 800, ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setBackgroundColor(mContext.getResources().getColor(R.color.tv6060));
        // 设置PopupWindow的遮罩层颜色
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        // 点击框外可以使得popupwindow消失
        popupWindow.setFocusable(true);
        //设置可以触摸弹出框以外的区域
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAsDropDown(data, 0, 0);
        // 设置背景颜色变暗
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = 0.5f;
        getWindow().setAttributes(lp);
        popupWindow.setOnDismissListener(() -> {
            WindowManager.LayoutParams lp1 = getWindow().getAttributes();
            lp1.alpha = 1f;
            getWindow().setAttributes(lp1);
        });

        sourceAdapter.setOnItemClickListener((position, string) -> {
            if (ds == 1) {
                tvSelect.setText(string.getName());
                stationList.get(0).setType(position);
                tvSelect.setTextColor(mContext.getResources().getColor(R.color.tv333));

                strSelect = string.getName();
                pwsSelect = string.getPid();

                tvLine.setText("");
                tvLine.setTextColor(mContext.getResources().getColor(R.color.orange_salmon));
                GetPwsLine();
            }

            if (ds == 2) {
                tvLine.setText(string.getName());
                lineList.get(0).setType(position);
                tvLine.setTextColor(mContext.getResources().getColor(R.color.tv333));

                lineName = string.getName();
                lineId = string.getPid();
            }

            dismiss();
        });
    }

    private void dismiss() {
        if (popupWindow != null) {
            popupWindow.dismiss();
        }
    }

    private void GetPwsLine() {
        lineId = "";
        lineName = "";
        lineList = new ArrayList<>();
        LogUtils.e("TAG", "RPCGetGeoGrids" + pwsSelect);
        if (StringUtils.isEmpty(pwsSelect)) {
            ToastUtil.showNew(mContext, "请选择工务段");
            return;
        }

        HttpClient.getInstance().getData(CommonHttpConsts.GetPwsLine, "GetPwsLine").tag(this).params("pwsid", pwsSelect).execute(new HttpCallbackData() {

            @RequiresApi(api = Build.VERSION_CODES.O)
            @Override
            public void onSuccess(int code, String msg, String info) {
                LogUtils.e("TAG", "info:" + info);

                if (code == 200) {
                    if (!StringUtils.isEmpty(info)) {
                        String string = StringUtils.decompressForGzip(info);
                        LogUtils.e("TAG", "string:" + string);
                        ArrayList<Map> dataList = (ArrayList<Map>) JSONArray.parseArray(string, Map.class);
                        setLine(dataList);
                    }
                } else {
                    ToastUtil.show(msg);
                }
            }

            @Override
            public boolean showLoadingDialog() {
                return true;
            }

            @Override
            public Dialog createLoadingDialog() {
                return DialogUitl.loginAuthDialog(mContext);
            }

            @Override
            public void onError() {
                super.onError();
                ToastUtil.show(StringUtils.error_context);
            }
        });
    }

    public void setLine(ArrayList<Map> dataList) {
        if (dataList.size() > 0) {
            for (int i = 0; i < dataList.size(); i++) {
                ChooseBean chooseBean = new ChooseBean();
                chooseBean.setName(dataList.get(i).get("LineName") + "");
                chooseBean.setPid(dataList.get(i).get("LineId") + "");

                lineList.add(chooseBean);
            }
        }
    }

    public void imgDialog(String milepostStr) {
        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(mContext);
        android.app.AlertDialog dialog = builder.create();
        // 显示对话框前，设置全屏
        dialog.setOnShowListener(d -> {
            // 获取对话框窗口
            Window window = dialog.getWindow();
            if (window != null) {
                // 设置窗口的属性以全屏显示
                window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
                window.setBackgroundDrawableResource(android.R.color.transparent);
            }
        });

        LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.dialog_img_item, null);
        ImageView tvClose = v.findViewById(R.id.tvClose);
        CustomImageView imgYu1 = v.findViewById(R.id.imgYu1);
        dialog.setCanceledOnTouchOutside(true);//点击屏幕不消失

        if (!dialog.isShowing()) {//此时提示框未显示
            dialog.show();
        }
        //自定义的东西
        dialog.getWindow().setContentView(v);

        Glide.with(mContext).load(milepostStr).error(R.mipmap.icon_error).into(imgYu1);

        tvClose.setOnClickListener(v1 -> dialog.dismiss());
    }

    private void initLocation() {
        isLocation = false;
        if (locationManager != null) {
            locationManager = null;
        }
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        String locationProvider = "";
        if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        }
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        }
        LogUtils.v("TAG", "有权限，开始吧" + locationProvider);
        // 检查权限和服务是否可用
        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            if (ActivityCompat.checkSelfPermission(mActivity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                LogUtils.v("TAG", "有没有权限");
                return;
            }
            //LocationManager.NETWORK_PROVIDER  网络
            //LocationManager.GPS_PROVIDER  GPS
            locationManager.requestLocationUpdates(locationProvider, 3000, 0, locationListener);
        } else {
            LogUtils.v("TAG", "GPS is disabled");
        }
    }

    LocationListener locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            // 使用经纬度
            mLongitude = decimalFormat.format(location.getLongitude());
            mLatitude = decimalFormat.format(location.getLatitude());
            mAltitude = decimalFormat2.format(location.getAltitude());

//            double c[] = GPSToGCJ.wgs84ToGcj02(location.getLatitude(), location.getLongitude());
//            LogUtils.d("d", c[0] + "," + c[1]);//高德位置
//            if (c.length > 1) {
//                mLongitude = decimalFormat.format(c[1]);
//                mLatitude = decimalFormat.format(c[0]);
//            }
//            double d[] = GPSToGCJ.gcj02ToBd09(c[0], c[1]);
//            LogUtils.d("d", "baidu：" + d[0] + "," + d[1]);//百度位置


            LogUtils.v("TAG", "经纬度：" + mLongitude + " " + mLatitude + " " + mAltitude);

            //GPSToGCJ.getAddress(location);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }

        @Override
        public void onProviderEnabled(String provider) {
            // 用户启用GPS时调用
            LogUtils.v("TAG", "onProviderEnabled：" + provider);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // 用户禁用GPS时调用
            LogUtils.v("TAG", "onProviderDisabled：" + provider);
        }
    };

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_LOCATION_PERMISSION_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，可以进行位置相关的操作
                initLocation();
            } else {
                // 权限被拒绝，可以提示用户手动开启权限或进行其他处理
                ToastUtil.show("定位权限授权失败");
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_IMG) {
                Bundle extras = data.getExtras();
                Map dataMap = new HashMap();
                dataMap.put("isBt", 1);//1：未提交 2：提交
                dataMap.put("p_time", StringUtils.getTimeS());
                dataMap.put("img", extras.get("data"));
                dataMap.put("type", 1);
                imgList.add(dataMap);
                imgAdapter.setData(imgList);
            }
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        LogUtils.e("TAG", "onStart");
//        if (!isLocation) {
//            if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
//                ActivityCompat.requestPermissions(mActivity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION_PERMISSION_CODE);
//            } else {
//                LogUtils.e("TAG", "权限已经授予");
//                // 权限已经授予，可以进行位置相关的操作
//                initLocation();
//            }
//        }
    }

    @Override
    protected void onDestroy() {
        LogUtils.e("TAG", "onDestroy");
        if (locationManager != null) locationManager.removeUpdates(locationListener);
        isLocation = true;
        super.onDestroy();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if ((System.currentTimeMillis() - mExitTime) > 2000) {
                ToastUtil.show("再按一次退出程序");
                mExitTime = System.currentTimeMillis();
            } else {
                ScreenManager.getScreenManager().exit();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}
